<template>
  <div>
    <div :id="toolbarId" style="border:1px solid #ddd;"></div>
    <div :id="editorId" style="height: 310px; border: 1px solid #ddd;"></div>
  </div>
</template>

<script>
import { getToken } from '@/utils/auth';
import '@wangeditor/editor/dist/css/style.css';
import { createEditor, createToolbar } from '@wangeditor/editor';
import store from '@/store';
let editor = null;
let toolbar = null;
export default {
  props: ['value'],
  watch: {
    value: {
      handler: function (val) {
        if (val) {
          this.html = val;
        }
      },
      immediate: true,
    },
  },
  data() {
    return {
      html: '',
      editorId:`w-e-${Math.random().toString().slice(-5)}`,
      toolbarId:`w-t-${Math.random().toString().slice(-5)}`,
    };
  },
  mounted() {
    this.$nextTick(() => {
      this.init();
    });
  },
  methods: {
    init() {
      const editorConfig = { MENU_CONF: {} };
      editorConfig.placeholder = '请输入内容';
      editorConfig.onChange = (editor) => {
        // 当编辑器选区、内容变化时，即触发
        // console.log('content', editor.children)
        // console.log('html', editor.getHtml())
        this.$emit('input', editor.getHtml());
      };
      editorConfig.MENU_CONF['uploadImage'] = {
        server: '/admin/file/wangeditorimg',
        fieldName: 'file',
        meta: {
          token: getToken(),
        },
        customInsert(res, insertFn) {
          insertFn(store.getters.domain + res.data);
        },
      };

      // 创建编辑器
      editor = createEditor({
        html: this.html,
        selector: '#'+this.editorId,
        config: editorConfig,
        mode: 'default', // 或 'simple' 参考下文
      });
      console.log(editor.getMenuConfig('uploadImage'), 'uploadImage');
      // 创建工具栏
      toolbar = createToolbar({
        editor,
        selector: '#'+this.toolbarId,
        mode: 'default', // 或 'simple' 参考下文
      });
    },
  },
};
</script>

<style scoped></style>
